import React, { useState, useEffect, useRef } from 'react';
import { Button, message, Row, Radio, Modal, Divider } from 'antd';
import { history } from 'umi';
import { TimeHeader, TableOkr } from './index/components/index';
import styles from './index/index.less';

const IndexPage = () => {
  let mode_local = localStorage.getItem('okr_category');
  const [mode, setMode] = useState(mode_local ? mode_local : '0');
  const [showList, setShowList] = useState([]);
  const [createOkrVisible, setCreateOkrVisible] = useState(false);
  const [master, setMaster] = useState('ling sang');
  const [okrId, setOkrId] = useState(0);
  const [jurisdiction, setJurisdiction] = useState('1');
  const [category, setCategory] = useState('0');
  const [okrCategory, setOkrCategory] = useState(mode);
  const [okrDepartmentId, setOkrDepartmentId] = useState(); // 创建多个部门 选择其中一个
  const [okrDepartmentList, setOkrDepartmentList] = useState([]);
  const [okrEditCount, setOkrEditCount] = useState(0);
  const [departmentname, setDepartmentname] = useState();

  const getTimeRef = useRef();

  useEffect(() => {
    initData();
  }, []);
  useEffect(() => {
    localStorage.removeItem('quarter');
    const num = okrEditCount + 1;
    setOkrEditCount(num);
  }, [mode]);
  const initData = async () => {
    // const { year, quarter } = getTimeRef.current;
    // if(year && quarter) {
    //   getData(year, quarter)
    // }
    getData(2022, 'q1');
  };

  const getData = async (year, quarter) => {
    const params = {
      type: mode === '0' ? '' : 'personal',
      year,
      quarter,
    };
    const okrList = [
      {
        key: 0,
        oname: '目标',
        oprogress: '10',
        oupdateTime: '2022-8-9',
        master: 'yy',
        type: '0',
        oweight: '20',
        oscore: '20',
        orelation: '',
        okrDetailPoList: [
          {
            progress: '78',
            content: 'jadd',
            updateTime: '2092-10-2',
            confidence: 8,
            weight: 89,
            score: 78,
            krRelationList: '[]',
          },
          {
            progress: '67',
            content: 'sss',
            updateTime: '2018-7-2',
            confidence: 8,
            weight: 72,
            score: 98,
            krRelationList: '[]',
          },
        ],
      },
      {
        key: 1,
        oname: '目标y',
        oprogress: '23',
        oupdateTime: '2021-1-9',
        master: 'ss',
        type: '0',
        oweight: '70',
        oscore: '80',
        orelation: '',
        okrDetailPoList: [],
      },
    ];
    // const okrList = await getOkrlist(params);
    setShowList(okrList || []);
    // setMaster(okrList?.master)
    // setCategory(okrList?.category)
    // setOkrId(okrList?.id)
  };

  const goNewOkrPage = async () => {
    // 发送权限接口
    // const res = await checkPermission();
    // if(res.num == '0') { // 只能创建个人OKr
    //   message.warning('当前登录用户权限仅能创建个人OKR')
    //   history.push({
    //     pathname: '/okr-detail',
    //     query: {
    //         departmentId: '',
    //         category: '1',
    //     }
    //   })
    // } else {
    //   setCreateOkrVisible(true)
    //   setDepartmentname(res.departmentname);
    //   const departmentList = res?.department || [];
    //   setOkrDepartmentList(departmentList)
    //   if(departmentList.length > 0) {
    //     setOkrDepartmentId(departmentList[0].code);
    //   }
    // }
  };

  const updateList = (year, quarter) => {
    if (year && quarter) {
      getData(year, quarter);
    }
  };
  const goOkrDetail = (obj) => {
    // const { year, quarter } = getTimeRef.current;
    // const ownList = obj?.onameList || [];
    // localStorage.setItem('okr_category', mode);
    // localStorage.setItem('year', year);
    // localStorage.setItem('quarter', quarter);
    // if(ownList.length > 0) {
    //   history.push({
    //     pathname: '/okr-detail',
    //     query: {
    //         id: ownList[0].okrid,
    //         // departmentId: departmentId,
    //         category: mode,
    //     }
    //   })
    // } else {
    //   message.success(`当前${obj.departmentLevel !== '0' ? '部门' : '个人'}无OKR`)
    // }
  };
  // const changeDepartmentId = (id) => {
  //   setDepartmentId(id[0])
  // }
  const handleOk = () => {
    history.push({
      pathname: '/okr-detail',
      query: {
        category: okrCategory, // 创建个人还是部门
        departmentId:
          okrCategory === '0'
            ? okrDepartmentList.length > 0
              ? okrDepartmentId
              : ''
            : '',
      },
    });
  };

  return (
    <div className={styles.all_okr_wrap}>
      <div className={styles.okr_right_wrap}>
        <Row style={{ marginBottom: '15px' }}>
          <TimeHeader
            updateList={updateList}
            ref={getTimeRef}
            mode={mode}
            okrEditCount={okrEditCount}
          ></TimeHeader>
          <Button
            style={{ float: 'right' }}
            type="primary"
            onClick={goNewOkrPage}
          >
            创建OKR
          </Button>
        </Row>
        <div
          style={{ background: '#fff', padding: '10px' }}
          className={styles.okr_right_body}
        >
          <Radio.Group
            onChange={(e) => {
              setMode(e.target.value);
              localStorage.removeItem('okr_category');
            }}
            value={mode}
            style={{ marginBottom: 8 }}
          >
            <Radio.Button value="0">部门OKR</Radio.Button>
            <Radio.Button value="1">个人OKR</Radio.Button>
          </Radio.Group>
          <Row>
            <TableOkr
              goOkrDetail={goOkrDetail}
              okrId={okrId}
              jurisdiction={jurisdiction}
              list={showList}
              master={master}
              category={category}
            />
          </Row>
        </div>
        {createOkrVisible && (
          <Modal
            title="请选择创建OKR类型"
            visible={createOkrVisible}
            onOk={handleOk}
            onCancel={() => {
              setCreateOkrVisible(false);
            }}
          >
            <Radio.Group
              onChange={(e) => {
                setOkrCategory(e.target.value);
              }}
              value={okrCategory}
            >
              <Radio value="0">部门OKR</Radio>
              <Radio value="1">个人OKR</Radio>
            </Radio.Group>
            {okrCategory === '0' && okrDepartmentList.length > 0 && (
              <>
                <Divider />
                <Radio.Group
                  onChange={(e) => {
                    setOkrDepartmentId(e.target.value);
                  }}
                  value={okrDepartmentId}
                >
                  {okrDepartmentList.map((item, index) => (
                    <Radio value={item.code}>{item.name}</Radio>
                  ))}
                </Radio.Group>
              </>
            )}
            {okrCategory === '1' && (
              <>
                <Divider />
                <Radio.Group value={departmentname}>
                  <Radio value={departmentname}>{departmentname}</Radio>
                </Radio.Group>
              </>
            )}
          </Modal>
        )}
      </div>
    </div>
  );
};

export default IndexPage;
